const jwt = require('jsonwebtoken')
const fs = require('fs');
const path = require('path')
const log = require('../utils/log')


function auth(req, res, next) {
  if (req.session.username) {
    try {
      let token = req.get('x-access-token');
      //对称
      // let rs = jwt.verify(token, 'lagouadmin')

      //非对称
      let publicKey = fs.readFileSync(path.resolve(__dirname, '../key/rsa_public_key.pem'));
      let rs = jwt.verify(token, publicKey, { algorithm: 'RS256' })
      if (rs === req.session.username) {
        next();
      } else {
        res.send({
          code: 401,
          message: "非法访问"
        })
      }
    } catch (error) {
      log.error(req.session.username + " 登录失败 " + error.message)
      res.send({
        code: 401,
        message: "非法访问"
      })
    }
  } else {
    res.send({
      code: 401,
      message: "非法访问"
    })
  }
}

module.exports = auth;